<script setup>
import {onMounted, ref} from "vue";
import {use} from 'echarts/core';
import {CanvasRenderer} from 'echarts/renderers';
import {BarChart, LineChart, PieChart} from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent, GridComponent,
} from 'echarts/components';
import VChart from 'vue-echarts';
import axios from "axios";
import {loginUser, ServerHost} from "@/main.ts";
import {ElNotification} from "element-plus";
import dayjs from "dayjs";
import {UniversalTransition} from "echarts/features";

// 懒加载
const goodsList = ref([])
const orderList = ref([])
const goodsSalesList = ref([])
const orderMonthSalesMap = ref(new Map())
const orderMonthSalesKeyList = ref([])
const orderMonthSalesValueList = ref([])
const observerDiv = ref(null)
const hasLoad = ref(false)
onMounted(() => {
  const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (entry.isIntersecting) {
        if (!hasLoad.value) {
          loadList()
        }
      }
    });
  });
  observer.observe(observerDiv.value);
})

const loadList = () => {

  // 商家的商品列表
  axios.get(`${ServerHost}/getSellerGoodsList?sellerId=${loginUser.value.id}`)
      .then((res) => {
        if (res.status === 200) {
          goodsList.value = res.data;
          goodsList.value.forEach(goods => {
            goodsSalesList.value.push({
              value: goods.sales,
              name: goods.name,
            })
          })
        } else {
          ElNotification({
            title: '商品获取失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })

  // 商家的订单列表
  axios.get(`${ServerHost}/getSellerOrderList?sellerId=${loginUser.value.id}`)
      .then((res) => {
        if (res.status === 200) {
          orderList.value = res.data.goodsOrderList;
          console.log(orderList.value)
          hasLoad.value = true
          orderList.value.reverse().forEach(order => {
            const year = dayjs(order.buyTime).year()
            // 月份是从 0 开始计算的，即 1 月是 0。
            const month = dayjs(order.buyTime).month() + 1
            let oldSales = orderMonthSalesMap.value.get(`${year}-${month}`)
            if (typeof (oldSales) === 'undefined' || oldSales == null)
              oldSales = 0
            orderMonthSalesMap.value.set(`${year}-${month}`, oldSales + 1)
          })
          console.log(orderMonthSalesMap.value)
          orderMonthSalesMap.value.forEach((value, key) => {
            orderMonthSalesKeyList.value.push(key)
            orderMonthSalesValueList.value.push(value)
          })
          console.log(orderMonthSalesKeyList.value)
          console.log(orderMonthSalesValueList.value)
        } else {
          ElNotification({
            title: '商品获取失败',
            type: 'error',
            position: 'bottom-right',
          })
        }
      })
}

use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  PieChart,
  CanvasRenderer,
  LineChart,
  UniversalTransition,
]);

// var cssVarColor = getComputedStyle(observerDiv).getPropertyValue('--el-color-primary');
// console.log(cssVarColor)

const option = {
  title: {
    text: '单品销量图'
  },
  tooltip: {
    trigger: 'item',
  },
  series: [
    {
      name: '',
      type: 'pie',
      data: goodsSalesList.value,
      radius: ['40%', '70%'],
      emphasis: {
        label: {
          show: true,
          fontSize: 20,
          color: getComputedStyle(document.documentElement).getPropertyValue('--el-color-primary'),
          fontWeight: 'bold'
        }
      },
    },
  ]
};

const option2 = {
  title: {
    text: '月销量图'
  },
  tooltip: {
    trigger: 'item',
  },
  xAxis: {
    type: 'category',
    data: orderMonthSalesKeyList.value
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '',
      type: 'line',
      data: orderMonthSalesValueList.value,
      smooth: true,
    },
  ]
};
</script>

<template>
  <div ref="observerDiv"/>
  <v-chart class="chart" :option="option" autoresize/>
  <v-chart class="chart" :option="option2" autoresize/>
</template>

<style scoped>
.chart {
  height: 300px;
}
</style>
